package com.zhihui.online.controller;


import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhihui.online.dto.admin.AdminInfoInsertDTO;
import com.zhihui.online.dto.admin.AdminInfoQueryDTO;
import com.zhihui.online.dto.admin.AdminInfoUpdateDTO;
import com.zhihui.online.dto.admin.AdminInfoUpdatePwdDTO;
import com.zhihui.online.entity.AdminInfo;
import com.zhihui.online.exception.MyCustomerException;
import com.zhihui.online.service.AdminInfoService;
import com.zhihui.online.utils.MD5Helper;
import com.zhihui.online.utils.Result;
import com.zhihui.online.utils.ResultCodeEnum;
import com.zhihui.online.vo.AdminInfoVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 * 管理员表 前端控制器
 * </p>
 *
 * @author 程序员阿良, 21岁纯情后爸, 懒得想名字
 * @since 2024-08-01
 */
@RestController
@RequestMapping("/online/admin-info")
@Api(tags = "管理员控制器")
public class AdminInfoController {

    @Resource
    public AdminInfoService adminInfoService;

    @ApiOperation("更改管理员状态")
    @GetMapping("/updateStatus/{id}/{status}")
    public Result<Object> updateStatus(@PathVariable Long id,
                                       @PathVariable Integer status) {
        if (id == null || status == null) {
            return Result.fail().message("参数缺失！");
        }
        this.adminInfoService.updateStatus(id, status);
        return Result.ok();
    }


    @ApiOperation("根据id 去获取管理员信息")
    @GetMapping("/findUserById/{id}")
    public Result<AdminInfoVO> findUserById(@PathVariable Long id) {
        AdminInfo adminInfo = this.adminInfoService.getById(id);
        if (adminInfo == null) {
            throw new MyCustomerException(ResultCodeEnum.USER_NOT_EXIST);
        }
        AdminInfoVO adminInfoVO = this.adminInfoService.getVO(adminInfo);
        return Result.ok(adminInfoVO);
    }

    @ApiOperation("修改管理员信息")
    @PostMapping("/updateAdminInfo")
    public Result<Object> updateUser(@RequestBody AdminInfoUpdateDTO adminInfoUpdateDTO) {
        //字段非空判断
        if (adminInfoUpdateDTO == null || adminInfoUpdateDTO.getId() == null) {
            throw new MyCustomerException(ResultCodeEnum.DATA_ERROR);
        }
        //转换为实体类
        AdminInfo adminInfo = new AdminInfo();
        BeanUtils.copyProperties(adminInfoUpdateDTO, adminInfo);
        boolean isSuccess = this.adminInfoService.updateById(adminInfo);
        return isSuccess ? Result.ok() : Result.fail();
    }

    @PostMapping("/addAdminInfo")
    @ApiOperation("添加管理员信息")
    public Result<Object> addUser(@RequestBody AdminInfoInsertDTO adminInfoInsertDTO) {
        //判断必要字段
        if (ObjectUtils.isEmpty(adminInfoInsertDTO) ||
                ObjectUtils.isNull(adminInfoInsertDTO.getUsername(), adminInfoInsertDTO.getPassword())) {
            throw new MyCustomerException(ResultCodeEnum.DATA_ERROR);
        }
        //判断账户是否已存在
        int username = this.adminInfoService.count(new QueryWrapper<AdminInfo>().eq("username", adminInfoInsertDTO.getUsername()));
        if (username >= 1) {
            throw new MyCustomerException(ResultCodeEnum.USER_EXIST);
        }
        // 通过MD5 工具类加密密码
        String passwordWithMD5 = MD5Helper.encrypt(adminInfoInsertDTO.getPassword());
        // 重新设置密码
        adminInfoInsertDTO.setPassword(passwordWithMD5);

        //拷贝数据并新增数据
        AdminInfo adminInfo = new AdminInfo();
        BeanUtils.copyProperties(adminInfoInsertDTO,adminInfo );
        boolean b = this.adminInfoService.save(adminInfo);
        return b ? Result.ok() : Result.fail();
        // todo 设置默认角色
//        if (b) {
//            //设置默认角色
//            SysUserRole sysUserRole = new SysUserRole();
//            sysUserRole.setUserId(sysUser.getId());
//            sysUserRole.setRoleId(1L);
//            this.sysRoleService.insertUserRole(sysUserRole);
//            return Result.ok();
//        }

//        return Result.fail();
    }

    @ApiOperation("分页和条件查询管理员信息9")
    @GetMapping("/{page}/{limit}")
    public Result<IPage<AdminInfoVO>> selectUserPageByVo(@PathVariable Long page,
                                     @PathVariable Long limit,
                                     AdminInfoQueryDTO adminInfoQueryDTO) {
        IPage<AdminInfoVO> iPage = new Page<>(page, limit);
        iPage = this.adminInfoService.selectPage(iPage, adminInfoQueryDTO);
        return Result.ok(iPage);
    }

    @ApiOperation("根据Id删除管理员信息")
    @DeleteMapping("/removeAdminInfoById/{id}")
    public Result<Object> removeUserByIds(@PathVariable Long id) {
        boolean isSuccess = this.adminInfoService.removeById(id);
        return isSuccess ? Result.ok() : Result.fail();
    }

    @ApiOperation("批量删除管理员信息")
    @DeleteMapping("/removeBatchAdminInfoByIds")
    public Result<Object> removeBatchUserByIds(@RequestBody List<Long> ids) {
        boolean isSuccess = this.adminInfoService.removeByIds(ids);
        return isSuccess ? Result.ok() : Result.fail();
    }

    @ApiOperation("修改用户密码")
    @PostMapping("/updatePassword")
    public Result<Object> updatePassword(@RequestBody AdminInfoUpdatePwdDTO updatePwdDTO){
        //判断是否为空
        if (ObjectUtil.isEmpty(updatePwdDTO)) {
            return Result.fail().message("参数缺失");
        }
        // 判断是否两次密码一致
        if (!updatePwdDTO.getNewPwd().equals(updatePwdDTO.getConfirmPwd())) {
            return Result.fail().message("两次密码不一致");
        }
        AdminInfo adminInfo = this.adminInfoService.getById(updatePwdDTO.getUserId());
        //判断用户是否存在
        if (adminInfo == null) {
            return Result.fail().message("用户不存在");
        }
        //新旧密码是否一致
        String encrypt = MD5Helper.encrypt(updatePwdDTO.getOldPwd());
        if (!adminInfo.getPassword().equals(encrypt)) {
            return Result.fail().message("旧密码不正确");
        }
        //封装存储对象
        AdminInfo adminInfo1 = new AdminInfo();
        adminInfo1.setId(updatePwdDTO.getUserId());
        adminInfo1.setPassword(MD5Helper.encrypt(updatePwdDTO.getNewPwd()));
        //更新数据
        boolean isSuccess = this.adminInfoService.updateById(adminInfo1);
        return isSuccess ? Result.ok() : Result.fail();
    }
}

